package com.mgee.netty.server.netty;

import com.mgee.netty.server.service.*;
import io.netty.channel.ChannelHandlerContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import com.google.protobuf.InvalidProtocolBufferException;
import com.mgee.netty.server.constant.MessagingConst;
import com.mgee.netty.server.pojo.SessionCloseReason;
import com.mgee.netty.server.protobuf.ImProto.ImMsg;
import com.mgee.netty.server.util.MessageBuilder;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;

/**
 * 请求分排器
 */
@Component
@Slf4j
public class MessageDispatcher{

	@Autowired
	@Qualifier(value = "LoginFlightServiceImpl")
	private LoginService flightLoginService;
	
	@Autowired
	@Qualifier(value = "LoginServiceImpl")
	private LoginService loginService;
	
	@Autowired
	private RoomService roomService;
	@Autowired
	private PlayerService playerService;
	@Autowired
	private LobbyService lobbyService;
	@Autowired
	private LobbyRoomService lobbyRoomService;
	@Autowired
	private CommandService commandService;
	@Autowired
	private ChatService chatService;

	@Resource
	private CloudCubeService cloudCubeService;
	
    /**
     * 消息分发处理
     *
     * @param gameMsg
     * @throws InvalidProtocolBufferException 
     */
	@Async
    public void dispatch(ImMsg imMsg, IoSession currSession, ChannelHandlerContext ctx) throws InvalidProtocolBufferException {

    	if(imMsg.getId() < 0) {
			log.info("error 接收到的消息ID是: "+imMsg.getId());
    		currSession.sendMessage(MessageBuilder.buildErrorResponse(imMsg, MessagingConst.RESPONSE_ERR_CODE_400, "Invalid message！"));
    		return;
    	}
    	//log.info("接收到的消息TypeUrl是: "+imMsg.getMsg().getTypeUrl());
        switch(imMsg.getMsg().getTypeUrl()) {
	        case MessagingConst.TYPE_LOGIN_FLIGHT_REQUEST:
	        	// 处理User登录请求
	        	flightLoginService.doLogin(imMsg, currSession);
	        	break;
	        case MessagingConst.TYPE_CREATE_PLAYER_REQUEST:
	        	// 处理创建人物请求
	        	playerService.createPlayer(imMsg, currSession);
	        	break;
	        case MessagingConst.TYPE_JOIN_LOBBY_REQUEST:
	        	// 处理加入大厅请求
	        	lobbyService.JoinLobby(imMsg, currSession);
	        	break;
	        case MessagingConst.TYPE_LEAVE_LOBBY_REQUEST:
	        	// 处理离开大厅请求
	        	lobbyService.leaveLobby(imMsg, currSession);
	        	break;
	        case MessagingConst.TYPE_LOBBY_INFO_REQUEST:
	        	// 处理查询大厅信息请求
	        	lobbyService.requestLobbyInfo(imMsg, currSession);
	        	break;
	        case MessagingConst.TYPE_JOIN_LOBBYROOM_REQUEST:
	        	// 处理加入大厅房间请求
	        	lobbyRoomService.joinRoom(imMsg, currSession);
	        	break;
	        case MessagingConst.TYPE_LEAVE_LOBBYROOM_REQUEST:
	        	// 处理离开大厅房间请求
	        	lobbyRoomService.leaveRoom(imMsg, currSession);
	        	break;
	        case MessagingConst.TYPE_UPDATE_LOBBYROOM_REQUEST:
	        	// 处理更新大厅房间信息请求
	        	lobbyRoomService.updateRoomInfo(imMsg, currSession);
	        	break;
	        case MessagingConst.TYPE_START_GAME_REQUEST:
	        	// 处理StartGame请求
	        	lobbyRoomService.startGame(imMsg, currSession);
	        	break;
	        case MessagingConst.TYPE_PUSH_TASKINFO_REQUEST:
	        	// 处理Push Task请求
	        	lobbyRoomService.pushTaskInfo(imMsg, currSession);
	        	break;
	        case MessagingConst.TYPE_TRANSMISSION_SYNC_REQUEST:
	        	// 处理TransmissionSyncRequest请求
	        	lobbyRoomService.transmissionSync(imMsg, currSession);
	        	break;
	        	
	        case MessagingConst.TYPE_LOGIN_REQUEST:
	        	// 处理登录请求
	        	loginService.doLogin(imMsg, currSession);
	        	break;
	        case MessagingConst.TYPE_LIST_ROOM_REQUEST:
	        	// 处理List Room请求
	        	roomService.listRoom(imMsg, currSession);
	        	break;
	        case MessagingConst.TYPE_JOIN_ROOM_REQUEST:
	        	// 处理Join Room请求
	        	roomService.joinRoom(imMsg, currSession);
	        	break;
	        case MessagingConst.TYPE_EXIT_ROOM:
	        	// 处理Exit Room请求
	        	roomService.exitRoom(imMsg, currSession);
	        	break;
	        case MessagingConst.TYPE_LOGOUT:
	        	// 处理Logout请求
	        	loginService.doLogout(imMsg, currSession);
	        	break;
	        case MessagingConst.TYPE_UPOS_REQUEST:
	        	// 处理UpPos请求
	        	roomService.updateUser(imMsg, currSession);
	        	break;
	        case MessagingConst.TYPE_GAME_COMMAND:
	        	// 处理Command请求
	        	commandService.dispatch(imMsg, currSession);
	        	break;
	        case MessagingConst.TYPE_CHAT_REQUEST:
	        	// 处理ChatRequest请求
	        	chatService.sendMessage(imMsg, currSession);
	        	break;
			case MessagingConst.TYPE_CLOUD_CUBE_BROADCAST:
				cloudCubeService.broadcast(imMsg, currSession, ctx);
				break;

			case MessagingConst.TYPE_CARD_ABC_LOGIN_REQUEST:
				cloudCubeService.handleCardAbcLogin(imMsg, currSession);
				break;
			case MessagingConst.TYPE_CARD_ABC_JOIN_REQUEST:
				roomService.newJoinCardRoom(imMsg, currSession);
				break;
			case MessagingConst.TYPE_CARD_ABC_BROADCAST_REQUEST:
				cloudCubeService.cardBroadcast(imMsg, currSession);
				break;
	        default:
	        	if(currSession != null) {
	        		// 返回客户端发来的心跳消息
		        	responseHeartbeat(imMsg, currSession);
	        	}
	        	break;
        }
    }
    
	/**
	 * 发送心跳包消息
	 * @param gameMsg
	 * @param currSession
	 * @return
	 */
	public boolean sendHeartbeat(IoSession currSession) {
		
		try {
			if(currSession.isHeartbeated()) {
				return false;
			}
			ImMsg.Builder imMsgBuilder = ImMsg.newBuilder();
			
			currSession.sendMessage(imMsgBuilder.build());
			
			currSession.setHeartbeated(true);
			
			return true;
		}catch(Exception e) {
			log.error("主动发送心跳包时发生异常：", e);
			currSession.close(SessionCloseReason.EXCEPTION);
			return false;
		}
		
	}
	/**
	 * 返回客户端发来的心跳包消息
	 * @param imMsg
	 * @param currSession
	 */
	private void responseHeartbeat(ImMsg imMsg,IoSession currSession) {
		//ImMsg.Builder imMsgBuilder = ImMsg.newBuilder();
		
		currSession.sendMessage(imMsg);
	}
	
}